package com.mobox.test;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import javax.xml.validation.Validator;


/**
 * Created by ${Clei} on 2018/5/10.
 */

public class

RockerRelativeLayout extends RelativeLayout {
    private RockerViews mRockerView;
    private int l;
    private int t;
    private int r;
    private int b;

    public RockerRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initRockerView(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            l = mRockerView.getLeft();
            t = mRockerView.getTop();
            r = mRockerView.getRight();
            b = mRockerView.getBottom();
            moveViewBylayout(mRockerView, (int) event.getX(), (int) event.getY());
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            mRockerView.layout(l, t, r, b);
        }
        //将layout的MotionEvent 事件传递给RockerView
        mRockerView.onTouchEvent(event);
        return true;
    }

    /**
     * Down 时移动到所点击的位置
     *
     * @param view RockerView
     * @param x    RelativeLayout的 X 坐标
     * @param y    RelativeLayout的 Y 坐标
     */
    private void moveViewBylayout(View view, int x, int y) {
        int rockerRadius = view.getWidth() / 2;
        int width = getWidth();

        int left = x - rockerRadius;
        int top = y - view.getHeight() / 2;
        int right = left + view.getWidth();
        int bottom = top + view.getHeight();

        if (type == 1) {
            if (right > width) {
                view.layout(width - rockerRadius * 2, top, width, bottom);
            } else {
                view.layout(left, top, right, bottom);
            }
        } else if (type == 2) {

            if (left < 0) {
                view.layout(0, top, right + rockerRadius, bottom);
            } else {
                view.layout(left, top, right, bottom);
            }
        }
    }

    int type = 0;

    /**
     * 初始化虚拟摇杆
     */
    private void initRockerView(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RockerRelativeLayout);
        type = typedArray.getInt(R.styleable.RockerRelativeLayout_rockerType, 0);
        mRockerView = new RockerViews(context, type);
        addView(mRockerView);
    }
}
